package com.atguigu.lease.web.admin.custom.converter;


import com.atguigu.lease.model.enums.BaseEnum;
import org.springframework.core.convert.converter.Converter;
import org.springframework.core.convert.converter.ConverterFactory;
import org.springframework.stereotype.Component;

//自定义转换器工厂，自动创建转换器
@Component
public class StringToBaseEnumConverterFactory implements ConverterFactory<String, BaseEnum> {

    @Override
    public <T extends BaseEnum> Converter<String, T> getConverter(Class<T> targetType) {
        return new Converter<String, T>() {
            @Override
            public T convert(String source) {
                //枚举对象.values 可以获取枚举对象内部的具体对象类型集合
                for (T enumConstant : targetType.getEnumConstants()) {
                    if (enumConstant.getCode() == Integer.parseInt(source)) {
                        return enumConstant;
                    }
                }
                throw new RuntimeException("数据类型错误!!!");
            }
        };
    }
}
